package org.jeyam.date;

import org.apache.commons.lang.time.DateUtils;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.form.AjaxFormComponentUpdatingBehavior;
import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.model.LoadableDetachableModel;
import org.apache.wicket.model.PropertyModel;

import java.util.Date;

/**
 * Created with IntelliJ IDEA.
 * User: madasamy
 * Date: 12/1/12
 * Time: 2:17 PM
 * To change this template use File | Settings | File Templates.
 */
public class DateAppPage extends WebPage {
    private DateApp dateClass = new DateApp();
    private TextField givenDateFiled;
    private TextField expectedDateField;

    public DateAppPage()
    {
        dateClass.setDays(1);
        dateClass.setGivenDate(new Date());
        add(createForm());
    }

    private Form createForm()
    {

        Form form = new Form("form");
        form.add(createTextField());
        form.add(createDaysField());
        form.add(createLabel());
        form.setOutputMarkupPlaceholderTag(true);
        return form;
    }


    private TextField createTextField()
    {
        givenDateFiled = new TextField<Date>("msgInput", new PropertyModel(dateClass, "givenDate"));
        givenDateFiled.setRequired(true);
        givenDateFiled.setOutputMarkupId(true);
        return givenDateFiled;
    }

    private TextField<Integer> createDaysField()
    {
        final TextField daysField = new TextField("days", new PropertyModel(dateClass, "days"));
        daysField.add(new AjaxFormComponentUpdatingBehavior("onchange")
        {
            @Override
            protected void onUpdate(AjaxRequestTarget target)
            {
                target.add(givenDateFiled);
                target.add(daysField);
                target.add(expectedDateField);
            }
        });
        daysField.setOutputMarkupId(true);

        return daysField ;
    }


    private TextField createLabel()
    {
        expectedDateField = new TextField("msg", new LoadableDetachableModel<Date>()
        {
            @Override
            protected Date load()
            {
                dateClass.setExpectedDate(DateUtils.addDays(dateClass.getGivenDate(), dateClass.getDays()));
                return dateClass.getExpectedDate();
            }
        });
        expectedDateField.setOutputMarkupId(true);
        return expectedDateField;
    }
}
